var audioBuffers = [];
var audioUrlList = [];
audioUrlList.push("sound/gun1.ogg");//------------------
audioUrlList.push("sound/gun1.ogg");//-----------------------
audioUrlList.push("sound/gun3_1.ogg");
audioUrlList.push("sound/machine_gun_loop2.ogg");
audioUrlList.push("sound/photon_rifle.ogg");
audioUrlList.push("sound/flame_thrower.wav");//5    старое
audioUrlList.push("sound/bullet_whiz1.ogg");//6
audioUrlList.push("sound/bullet_whiz2.ogg");
audioUrlList.push("sound/bullet_whiz3.ogg");
audioUrlList.push("sound/bullet_whiz4.ogg");
audioUrlList.push("sound/bullet_whiz5.ogg");
audioUrlList.push("sound/bullet_whiz6.ogg");
audioUrlList.push("sound/bullet_whiz7.ogg");
audioUrlList.push("sound/bullet_whiz8.ogg");//13
audioUrlList.push("sound/ricochet1.ogg");//14
audioUrlList.push("sound/ricochet2.ogg");
audioUrlList.push("sound/ricochet3.ogg");
audioUrlList.push("sound/ricochet4.ogg");
audioUrlList.push("sound/ricochet5.ogg");//18
audioUrlList.push("sound/knifes.wav");//19    старое
audioUrlList.push("sound/shotgun1.ogg");//20
audioUrlList.push("sound/shotgun2.ogg");//21
audioUrlList.push("sound/shotgun3.ogg");//22
audioUrlList.push("sound/overheat.ogg");//23
audioUrlList.push("sound/shield.wav");//24   старое
audioUrlList.push("sound/explosion.ogg");//25
audioUrlList.push("sound/bazooka.ogg");//26
audioUrlList.push("sound/grenade_throw.ogg");//27
audioUrlList.push("sound/double_gun1.ogg");//28
audioUrlList.push("sound/double_gun2.ogg");//29
audioUrlList.push("sound/double_gun3.ogg");//30
audioUrlList.push("sound/double_gun4.ogg");//
audioUrlList.push("sound/double_gun5.ogg");//
audioUrlList.push("sound/double_gun6.ogg");//
audioUrlList.push("sound/double_gun7.ogg");//
audioUrlList.push("sound/gun1.ogg");//35
audioUrlList.push("sound/gun2.ogg");//
audioUrlList.push("sound/gun3.ogg");//
audioUrlList.push("sound/gun4.ogg");//
audioUrlList.push("sound/gun5.ogg");//
audioUrlList.push("sound/gun6.ogg");//
audioUrlList.push("sound/gun7.ogg");//
audioUrlList.push("sound/gun8.ogg");//42
audioUrlList.push("sound/impact1.ogg");//43
audioUrlList.push("sound/impact2.ogg");//
audioUrlList.push("sound/impact3.ogg");//
audioUrlList.push("sound/impact4.ogg");//
audioUrlList.push("sound/impact5.ogg");//47
audioUrlList.push("sound/life_pack_taken.ogg");//48
audioUrlList.push("sound/photon_rifle_power_up2.ogg");//49
audioUrlList.push("sound/cheer_red_team.ogg");//50
audioUrlList.push("sound/cheer_blue_team.ogg");//51
audioUrlList.push("sound/enemy_took_flag.ogg");//52
audioUrlList.push("sound/flag_returned.ogg");//53
audioUrlList.push("sound/team_took_flag.ogg");//54
audioUrlList.push("sound/gun3_1.ogg");//55
audioUrlList.push("sound/overheat2.ogg");//56
//audioUrlList.push("sound/music.ogg");//57

var counterI = 0;
function preloadAudio() {
    for (var i = 0; i < audioUrlList.length; i++) {
        loadSound(audioUrlList[i], i);
    }
}
var gainNodeCommon = null;
var gainNodeWhiz = null;
var gainNode50 = null;
var audioWebKit = false;
var audioFirefox = false;
function endPeloadSound() {
    //playSound(57,gainNode50);
}
function audioInit() {
    try {

        context = new webkitAudioContext();
        audioWebKit = true;
        gainNodeCommon = context.createGainNode();
        gainNodeCommon.connect(context.destination);
        gainNodeCommon.gain.value = 0.5;
        gainNodeWhiz = context.createGainNode();
        gainNodeWhiz.connect(context.destination);
        gainNodeWhiz.gain.value = 0.1;
        gainNode50 = context.createGainNode();
        gainNode50.connect(context.destination);
        gainNode50.gain.value = 0.25;
        preloadAudio();
    }
    catch (e) {
        audioWebKit = false;
        browserDetect = browserDetectNav();
        if (browserDetect[0] == "Firefox") {
            preloadAudioMoz();
            audioFirefox = true;
        } else {
           alertDialog("Web Audio API не поддерживается Вашим браузером. Для игры со звуком используйте <span onclick=\"window.location = 'http://www.google.com/intl/ru/chrome/';\" style='color: #8d0000; cursor: pointer;'>Google Chrome</span>");
        }
    }
}
function loadSound(url, i) {
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.responseType = 'arraybuffer';
    // Decode asynchronously 
    request.onload = function() {
        context.decodeAudioData(request.response, function(buffer) {
            counterI++;
            //$("#loading .progressbar").progressbar("value", Math.floor((counterI/audioUrlList.length)*50));
            audioBuffers[i] = buffer;
            if (counterI == audioUrlList.length) {
                endPeloadSound();
            }
        }, function() {
            alert("error decodeAudioData " + url);
        });
    }
    request.send();
}
function playSound(bufferIndex, gainNode) {
    if (options.sound) {
        if (audioWebKit) {
            var source = context.createBufferSource();
            source.buffer = audioBuffers[bufferIndex];
            if (arguments.length == 1) {
                source.connect(gainNodeCommon);
            } else {
                source.connect(gainNode);
            }
            //source.connect(context.destination); 
            source.noteOn(0);
        } else if (audioFirefox) {
            try {
                playSoundMoz(bufferIndex);
            } catch (e) {
            }
        }
    }
}
function playRandomWhiz() {
    var randomWhiz = Math.floor(Math.random() * 8) + 6;
    playSound(randomWhiz, gainNodeWhiz);
}
function playRandomRic() {
    var randomWhiz = Math.floor(Math.random() * 5) + 14;
    playSound(randomWhiz, gainNodeWhiz);
}
function playRandomHit() {
    var random = Math.floor(Math.random() * 5) + 43;
    playSound(random);
}
function playRandomDualGun() {
    var random = Math.floor(Math.random() * 7) + 28;
    playSound(random);
}
function playRandomGun() {
    var random = Math.floor(Math.random() * 8) + 35;
    playSound(random);
}
function playRandomShotGun() {
    var random = Math.floor(Math.random() * 3) + 20;
    playSound(random);
}
//MOZILLA==================================
var sounds = [];
function loadedMetadata(i, audio) {
    sounds[i].channel = audio.mozChannels;
    sounds[i].rate = audio.mozSampleRate;
}
function audioAvailable(event, i) {
    for (var k = 0; k < event.frameBuffer.length; k++) {
        sounds[i].buffers.push(event.frameBuffer[k]);
        sounds[i].time = event.time;
    }
    /* if(i==2){
     alert(event.frameBuffer.length+" "+sounds[i].buffers.length);
     }*/
}
function preloadAudioMoz() {
    for (var i = 0; i < audioUrlList.length; i++) {
        if (i == 23 || i == 24 || i == 26 || i == 52 || i == 53 || i == 54 || i == 3 || i == 19 || i == 4 || i == 2 || i == 22 || i == 21 || i == 20 || i == 25) {
            setTimeout("loadSoundMoz(" + i + ")", 500 * i);
        } else {
            setTimeout("loadSoundMoz(" + i + ")", 200 * i);
        }
    }
}
function loadSoundMoz(i) {
    //$("#loading .progressbar").progressbar("value", Math.floor((i/audioUrlList.length)*50));
    if (i >= (audioUrlList.length - 1)) {
        endPeloadSound();
    }
    var audio = new Audio();
    sounds.push({
        buffers: [],
        rate: 44100,
        channel: 1,
        time: 0
    });
    audio.addEventListener('loadedmetadata', function() {
        loadedMetadata(i, audio);
    }, false);
    audio.addEventListener('MozAudioAvailable', function(e) {
        audioAvailable(e, i);
    }, false);
    audio.src = audioUrlList[i];
    audio.volume = 0;
    audio.play();
    return;
}
var output = [];
for (var h = 0; h < 10; h++) {
    output.push({
        audio: new Audio(),
        timeEnded: 0
    });
}
function playSoundMoz(bufferIndex) {
    if (bufferIndex >= 6 && bufferIndex <= 13) {
        return;
    }
    var time = new Date().getTime();
    for (var i = 0; i < output.length; i++) {
        if (time > output[i].timeEnded) {
            output[i].audio.mozSetup(sounds[bufferIndex].channel, sounds[bufferIndex].rate);
            output[i].audio.mozWriteAudio(sounds[bufferIndex].buffers);
            output[i].timeEnded = time + sounds[bufferIndex].time * 1000;
            return;
        }
    }
}
